#include <iostream>
#include "ex01-library.h"
using namespace std;

// Task 1(a).  Implement this function
Complex **createMatrix(unsigned int m, unsigned int n, Complex c) {
    // Write your code here
    // 二维数组动态内存分配 (x)
    Complex** matrix = new Complex*[m];
    for(int i=0; i<m; i++) {
        matrix[i] = new Complex[n];
    }
    // 初始化
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            matrix[i][j] = c;
        }
    }
    return matrix;
}

// Task 1(b).  Implement this function
void displayMatrix(Complex **A, unsigned int m, unsigned int n) {
    // Write your code here
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            cout << A[i][j].re << (A[i][j].im >= 0 ? "+" : "") << A[i][j].im << "i";
            cout << (j == n-1 ? "\n" : " ");
        }
    }

}

// Task 1(c).  Implement this function
Complex **createIdentityMatrix(unsigned int n) {
    // Write your code here
    Complex** matrix = createMatrix(n,n,{0,0});   
    for(int i=0; i<n; i++) {
        matrix[i][i] = {1,0}; 
    }
    return matrix;
}

// Task 1(d).  Implement this function
void multMatrix(Complex **A, Complex **B, Complex **C,
                unsigned int m, unsigned int n, unsigned int p) {
    // Write your code here
    for(int i=0; i<m; i++) {
        for(int j=0; j<p; j++) {
            for(int k=0; k<n; k++) {
                // C[i][j].re += mult(A[i][k],B[k][j]).re;
                // C[i][j].im += mult(A[i][k],B[k][j]).im;
                C[i][j] = add(C[i][j], mult(A[i][k],B[k][j]));
            }
        }
    }
}

// Do not modify
Complex add(Complex c, Complex d) {
    Complex result = { c.re + d.re, c.im + d.im };
    return result;
}

// Do not modify
Complex mult(Complex c, Complex d) {
    Complex result;
    result.re = (c.re * d.re) - (c.im * d.im);
    result.im = (c.re * d.im) + (c.im * d.re);
    return result;
}

// Do not modify
void deleteMatrix(Complex **A, unsigned int nRows) {
    for (unsigned int i = 0; i < nRows; i++) { delete[] A[i]; }
    delete[] A;
}
